import { createSlice } from "@reduxjs/toolkit";
// import axios from "axios";
import datajson from '../../json/data.json'

const foodsStore = createSlice({
    name:'foods',
    initialState:{
        foodsList:[],
        menuIndex:0,
        //购物车列表
        cartList:[]
    },
    reducers:{
        setFoodsList(state,action){
            //payload是默认的字段熟悉，获取传入的action的字段需要加上payload
            state.foodsList = action.payload;
        },
        setMenuIndex(state,action){
            //payload是默认的字段熟悉，获取传入的action的字段需要加上payload
            state.menuIndex = action.payload;

        },
        addCart(state,action){
            const item = state.cartList.find(item => item.id === action.payload.id);
            if(item){
                item.count++;
            }else{
                action.payload.count = 1;
                state.cartList.push(action.payload);
            }
        },
        increCount(state,action){
            const item = state.cartList.find(item => item.id === action.payload.id);
            if(item){
                item.count++;
            }
        },
        decreCount(state,action){
            const item = state.cartList.find(item => item.id === action.payload.id);
            if( item.count>0){
                item.count--;
            }
        },
        clearCart(state){
            state.cartList = [];
        }
    }
});

//解构
const { setFoodsList,setMenuIndex,addCart,increCount,decreCount,clearCart} = foodsStore.actions;

//异步部分
const getFoodList = ()=>{
    return async (dispatch)=>{
    //   const res =  await axios.get('http://localhost:3004/takeaway');
    console.log('datajson',datajson)
      dispatch(setFoodsList(datajson.takeaway))
    }
}

//提供给外部使用
export { getFoodList,setMenuIndex,addCart,increCount,decreCount,clearCart }

//需要在入口文件中引入
export default foodsStore.reducer;